package net.mikoo.seals.biz.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.mikoo.seals.biz.mapper.CompanyMapper;
import net.mikoo.seals.biz.mapper.DevicesActMapper;
import net.mikoo.seals.biz.mapper.PartyMapper;
import net.mikoo.seals.biz.mapper.PersonMapper;
import net.mikoo.seals.biz.model.PartyDetail;
import net.mikoo.seals.biz.model.PartyType;
import net.mikoo.seals.model.Company;
import net.mikoo.seals.model.CompanyQuery;
import net.mikoo.seals.model.DevicesAct;
import net.mikoo.seals.model.DevicesActQuery;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.model.Person;
import net.mikoo.seals.model.PersonQuery;

@Service
public class PartyManager {

	@Autowired
	private PartyMapper partyMapper;
	
	@Autowired
	private PersonMapper personMapper;
	
	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private DevicesActMapper devicesActMapper;
	
	public PartyDetail getDetail(Long partyId) {
		
		if(partyId == null) {
			throw new IllegalArgumentException("partyId");
		}
		
		Party party = partyMapper.selectByPrimaryKey(partyId);
		if(party == null) {
			return null;
		}
		PartyDetail result = new PartyDetail();
		result.setParty(party);
		
		if(party.getCompanyId() != null) {
			Company company = companyMapper.selectInfoById(party.getCompanyId());
			if(company != null) {
				result.setCompany(company);
			}
		}
		
		Person person = personMapper.selectByPartyId(partyId);
		if(person != null) {
			result.setPerson(person);
		}
		
		DevicesActQuery devicesActQuery = new DevicesActQuery();
		devicesActQuery.setPartyId(partyId);
		DevicesAct devicesAct = devicesActMapper.selectInfoByQuery(devicesActQuery);
		if(devicesAct != null) {
			result.setType(PartyType.DEVICES_ADMIN);
		}
		
		CompanyQuery companyQuery = new CompanyQuery();
		companyQuery.setUserLoginId(person.getUserLoginId());
		Company company = companyMapper.selectInfoByQuery(companyQuery);
		if(company != null) {
			result.setType(PartyType.SYSTEM_ADMIN);
		}
		
		if(result.getType() == null) {
			result.setType(PartyType.NORMAL);
		}
		
		return result;
	}
}
